<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\Auth as AuthModel;
use app\common\service\system\Captcha;

class Auth extends \app\BaseController
{
    /**
     * 登录接口
     */
    public function login()
    {
        if ($msg = dmjValidate([
            'username' => 'alphaDash',
            'code' => 'require',
        ],[
            'code.require' => '验证码错误'
        ],input('post.'))){
            return fail($msg);
        }

        if (!app()->make(Captcha::class)->check(input('code'))){
            return fail('验证码错误');
        }

        $admin = new Admin;
        $adminId = $admin->login(input('post.'));
        if (false === $adminId) {

            return fail($admin->getError());
        }

        $auth = new AuthModel;
        $token = $auth->getToken($adminId);
        if (false === $token) {
            return fail('token 生成失败，请刷新重试');
        }
        return success('登录成功', $token);
    }

    /**
     * 退出登录接口
     */
    public function logout()
    {
        $accessToken = $this->request->header('Authorization');
        $adminInfo = cache($accessToken);
        if (empty($adminInfo)) {
            return success('退出成功');
        }

        $auth = new AuthModel;
        $auth->deleteToken($accessToken);
        return success('退出成功');
    }

    /**
     * 刷新token
     */
    public function refreshToken()
    {
        $refreshToken = input('post.refresh_token');
        if (empty($refreshToken)) {
            return fail('refresh_token 不能为空');
        }
        $auth = new AuthModel;
        $token = $auth->refreshToken($refreshToken);
        if (false === $token) {
            return fail('刷新失败');
        }
        return success('刷新成功', $token);
    }


    public function getVerify(){
        return app()->make(Captcha::class)->create();
    }
}
